#include "BangoStorage.h"

QString BangoStorage::connectionName = "";

BangoStorage::BangoStorage()
{
    CreateConnection();
}

BangoStorage::~BangoStorage()
{
    if (dbBango.isOpen())
    {
        dbBango.close();
    }
}

void BangoStorage::CreateConnection()
{
    QString dbName(BangoConstants::DATABASE_NAME);
    dbName.append(QString::number(BangoConstants::DATABASE_VERSION));


    // Connection name is saved, so that once connection is created, it can be reused
    // rather than recreating a new connection every time
    if (connectionName > "" && QSqlDatabase::contains(connectionName))
    {
        dbBango = QSqlDatabase::database(connectionName, true);
    }
    else
    {
        dbBango = QSqlDatabase::addDatabase("QSQLITE");
        connectionName = dbBango.connectionName();
    }

#ifdef Q_OS_LINUX
    // NOTE: We have to store database file into user home folder in Linux
    QString path(QDir::home().path());
    path.append(QDir::separator()).append((dbName);
    path = QDir::toNativeSeparators(path);
    dbBango.setDatabaseName(path);
#else
    // NOTE: File exists in the application private folder, in Symbian Qt implementation
    dbBango.setDatabaseName(dbName);
#endif

    if (dbBango.open())
    {
        QSqlQuery query(dbBango);
        query.exec(BangoConstants::SQL_CREATE_TABLE);
    }

}

int BangoStorage::SaveRecord(QString jsonText)
{
    int newID = -1;
    bool ret = false;

    if (dbBango.isOpen())
    {
        QSqlQuery query(dbBango);
        ret = query.exec((BangoConstants::SQL_INSERT_INTO_TABLE)
                          .arg(jsonText));

        if (ret)
        {
            newID = query.lastInsertId().toInt();
        }
    }
    return newID;
}

QMap<int,QString> BangoStorage::GetRecords()
{
    QMap<int,QString> returnValues;

    if (dbBango.isOpen())
    {
        QSqlQuery query(dbBango);
        query.exec(BangoConstants::SQL_SELECT_FROM_TABLE);

        while (query.next())
        {
            returnValues[query.value(0).toInt()] = query.value(1).toString();
        }
    }

    return returnValues;
}


bool BangoStorage::DeleteRecord(int recordId)
{
    bool ret = false;

    if (dbBango.isOpen())
    {
        QSqlQuery query(dbBango);

        ret = query.exec((BangoConstants::SQL_DELETE_FROM_TABLE)
                          .arg(recordId));
    }

    return ret;
}
